#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<mysql/mysql.h>

void add(MYSQL* mysql)//添加数据
{
    char* sql = "insert into test_tb values(null,18,'小张',77.5);";
    int ret = mysql_query(mysql,sql);//执行sql语句
    if(ret!=0)
    {
        printf("query sql failed:%s\n",mysql_error(mysql));
    }
}
int mod(MYSQL* mysql)//修改数据
{
    char* sql = "update test_tb set name='小王' where id = 2;";
    int ret = mysql_query(mysql,sql);//执行sql语句
    if(ret!=0)
    {
        printf("query sql failed:%s\n",mysql_error(mysql));
        return -1;
    }
    return 0;
}
void del(MYSQL* mysql)//删除数据
{
    char* sql = "delete from test_tb where id = 2;";
    int ret = mysql_query(mysql,sql);//执行sql语句
    if(ret!=0)
    {
        printf("query sql failed:%s\n",mysql_error(mysql));
    }
}
void get(MYSQL* mysql)//查询数据
{
    char* sql = "select * from test_tb;";
    int ret = mysql_query(mysql,sql);//执行sql语句
    if(ret!=0)
    {
        printf("query sql failed:%s\n",mysql_error(mysql));
    }
    MYSQL_RES *res = mysql_store_result(mysql);//保存查询结果到本地
    if(res==NULL)
    {
        printf("store result failed:%s\n",mysql_error(mysql));
    }
    int row_num = mysql_num_rows(res);//获取行数
    int col_num = mysql_num_fields(res);//获取列数
    for(int i=0;i<row_num;i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);//遍历结果
        for(int j = 0;j<col_num;j++)
        {
            printf("%s\t",row[j]);
        }
        printf("\n");
    }
    mysql_free_result(res);//释放结果集
}


int main()
{
    MYSQL* mysql = mysql_init(NULL);//初始化操作句柄
    if(mysql_real_connect(mysql,"127.0.0.1","root","","test_db",0,NULL,0)==NULL)//连接mysql服务器
    {
        printf("connect mysql server failed\n");
    }
    mysql_set_character_set(mysql,"utf8");//设置客户端字符集

    //执行语句
    //add(mysql);
    //mod(mysql);
    //del(mysql);
    get(mysql);

    mysql_close(mysql);//关闭数据库
    return 0;
}
